package com.wushi.lenovo.asia5b.app_di.other.presenter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.mvp.base.BasePresenter;
import com.mvp.common.GlobalValue;
import com.mvp.common.LocalManageUtil;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.VersionManagerFragmentView;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_model.other.UpdateModel;

import java.util.Map;

import javax.inject.Inject;

import timber.log.Timber;


/**
 * Created by zhangyuncai on 2019/4/18.
 */
public class VersionManagerFragmentPresenter extends BasePresenter<VersionManagerFragmentView> {

    ApiService apiService;

    @Inject
    public VersionManagerFragmentPresenter(ApiService apiService) {
        this.apiService = apiService;
    }


    public void setAppInfo(Map<String, Object> map) {
        baseSubscribe(apiService.setAppInfo(map),
                resultModel -> {
                    getView().setAppInfoResult(resultModel);
                });
    }

    public void getAppInfo(Activity activity,String type) {
        if (GlobalValue.isDebug) {
            UpdateModel data = new UpdateModel();
            data.setBuild("1018");
            data.setUpdate_url("https://fir.im/596y");
            if (data != null) {

                try {
                    PackageInfo packageInfo = getPackageInfo(activity);
                    long netBuild = Long.parseLong(data.getBuild());
                    long localBuild = 0;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                        localBuild = packageInfo.getLongVersionCode();
                    } else {
                        localBuild = packageInfo.versionCode;
                    }
                    Timber.d("--->>>>>>>>---netBuild:" + netBuild);
                    Timber.d("--->>>>>>>>---localBuild:" + localBuild);
                    if (netBuild > localBuild) {
                        updateDialog(data, activity);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        baseSubscribe(apiService.getAppInfo(type, LocalManageUtil.getAppLanguage()),
                resultModel -> {
                    getView().getAppInfoResult(resultModel);


                    if (resultModel.isSuccess()&&resultModel.getData()!=null&&resultModel.getData().size()>0) {
                        UpdateModel data = resultModel.getData().get(0);
                        if (data != null) {

                            try {
                                PackageInfo packageInfo = getPackageInfo(activity);
                                long netBuild = Long.parseLong(data.getBuild());
                                long localBuild = 0;
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                    localBuild = packageInfo.getLongVersionCode();
                                } else {
                                    localBuild = packageInfo.versionCode;
                                }
                                Timber.d("--->>>>>>>>---netBuild:" + netBuild);
                                Timber.d("--->>>>>>>>---localBuild:" + localBuild);
                                if (netBuild > localBuild) {
                                    updateDialog(data, activity);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }

                });
    }

    private PackageInfo getPackageInfo(Context context) {
        PackageInfo pi;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new PackageInfo();
    }

    private void updateDialog(UpdateModel updateModel, Activity activity) {

        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        AlertDialog alertDialog = builder.setTitle("请更新至最新版本!")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.equals(updateModel.getForce_update(), "1")) {//强制升级
                            System.exit(0);
                        }
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!TextUtils.isEmpty(updateModel.getUpdate_url())) {//有跳转地址就跳跳转地址
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(updateModel.getUpdate_url()));
                            activity.startActivity(intent);
                        } else {//否则直接跳谷歌商城
                            downloadApp(activity, activity.getPackageName());
                        }
                    }
                })
                .setMessage(updateModel.getChangelog())
                .create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();

    }

    //跳转谷歌下载
    private void downloadApp(Context context, String appPkg) {    //appPkg 是应用的包名
        final String GOOGLE_PLAY = "com.android.vending";//这里对应的是谷歌商店，跳转别的商店改成对应的即可
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GOOGLE_PLAY);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            //Toast.makeText(context, "", Toast.LENGTH_SHORT).show();   //跳转失败的处理
        }
    }
}